﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Text;
using System.Windows.Forms;
using System.Management.Automation.Runspaces;
using System.Management.Automation;
using System.Collections.ObjectModel;

namespace PoSHEditor
{
    public partial class PoSHEditor : UserControl
    {
        public PoSHEditor()
        {
            InitializeComponent();
        }

        private void txtScript_TextChanged(object sender, EventArgs e)
        {
            if (useImmediateModeToolStripMenuItem.Checked)
                Execute();
        }

        public void Execute()
        {
            if (InvokeRequired)
            {
                throw new Exception("Cannot call execut recursively");
            }
            else DoExecute();
        }
        
        void DoExecute()
        {
            Singletons.TheScriptEngine.AddOutString(true);
            InvokeScriptResults results = Singletons.TheScriptEngine.InvokeScriptWithResults(txtScript.Text);

            txtErrors.Text = txtResults.Text = "";

            if (results.Exception == null)
                txtResults.Text = results.PSObjects[0].BaseObject.ToString();

            else
                txtErrors.Text = results.Exception.Message;
        }

        public void SetVariable(string name, object value)
        {
            Singletons.TheScriptEngine.SetVariable(name, value);
        }

        public string ScriptText
        {
            get { return txtScript.Text; }
            set {
                if (InvokeRequired)
                {
                    BeginInvoke(new MethodInvoker(delegate()
                    {
                        txtScript.Text = value;
                    }));
                }
                else
                    txtScript.Text = value; 
            }
        }

        private void txtScript_KeyUp(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.F5)
                Execute();            
        }

        private void useImmediateModeToolStripMenuItem_Click(object sender, EventArgs e)
        {
            useImmediateModeToolStripMenuItem.Checked = !useImmediateModeToolStripMenuItem.Checked;
        }
    }
}